<?php

namespace app\common\model;

use fast\Time;
use traits\model\SoftDelete;
use think\Model;
use think\Db;

class Sales extends Model
{
    use SoftDelete;
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $deleteTime = 'delete_time';
    protected $createTime = 'create_time';
    
    //表名
    protected $name = 'sales';

    /**
     * [calendar 日历模式数据]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-25
     * @param    [type]      $goods_id [产品id]
     * @param    string      $format   [description]
     * @return   [type]                [description]
     */

    public function calendar($goods_id,$format = 'Y-n-j')
    {
        
        $list = $this->where(['goods_id' => $goods_id,'sales_status' => 1])->find();
        $timeList[] = $this->getTimeList($list['startTime'], $list['endTime'], $list,$format);
        $calendar = [];
        foreach ($timeList as $k => $v) {
            foreach ($v as &$value) {
                $calendar[] = $value;
            }
        }
        return $calendar;
    }

    

    /**
     * @param array $where
     * @return mixed
     * 在同一商品获取某销售方案门市价格
     */
    public static function retail_price($where = [])
    {
        $where['sales_status'] = 1;
        $list = collection(self::where($where)->field('retailPrice')->select())->toArray();
        $list = array_column($list,'retailPrice');
        return reset($list);
    }


    /***
     * 参数分别是开始时间戳，结束时间戳
     */
    public function getTimeList($beginTimeStamp, $endTimeStamp, $data = [],$format = 'Y-n-j')
    {
        $dayModel   = new  \app\store\model\DayInventory();
        $goodsModel = new Goods();
        $deadlineType = $goodsModel->where('id',$data['goods_id'])->value('deadlineType');//有效期
        $validPeriod  = $goodsModel->validity_period($data['goods_id']);       //自定义有效时间段

        if (!is_numeric($beginTimeStamp) || !is_numeric($endTimeStamp) || ($endTimeStamp <= $beginTimeStamp))
            return '';
        $weeks = explode(',', $data['workdayData']);
         
        //开始是否小于今天  
        $today = strtotime(date("Y-m-d"));
        if ($beginTimeStamp < $today) {
           $beginTimeStamp  = $today;
        }

        //大于45天
        $day30 = $today+3888000;
        if ($endTimeStamp > $day30) {
            $endTimeStamp = $day30;
        }
        $goods = $goodsModel->get($data['goods_id']);

        $tmp = array();
        for ($i = $beginTimeStamp; $i <= $endTimeStamp; $i += (24 * 3600)) {
            // $tmp['timeStampList'][]=$i;
            //$tmp['dayList'][]=date('Y-m-d',$i);
            $check_time_end = $goodsModel->checkInTimeEnd($i,$data['goods_id']);//验票时间结束

            if ($goods['before'] > 0) {
                $reserve = $goodsModel->reserve($goods,$i);//提前预定判断
            }else{
                $reserve = true;
            }
            
            if ($deadlineType == Goods::DEADLINETYPE_2 ){
                //有效期不受提前预定判断影响
                $reserve = true;
            }
            if ($goods['is_day_stock']) {
                //单日数据
                $day = $dayModel->where(['goods_id'=>$data['goods_id'],'day_time'=>$i])->find();
            }else{
                $day = [];
            }

            if (in_array(date('w', $i), $weeks)) {
                if($day){
                    if ($day['oneStock'] != -2) {
                        $tmp[$i]['day_id']       = $day['id'];//单日表id
                        $tmp[$i]['sales_id']     = $data['id'];//销售方案id
                        $tmp[$i]['date']         = date($format, $i);
                        $tmp[$i]['cost_price']   = $day['cost_price'];
                        $tmp[$i]['sale_price']   = $day['sale_price'];
                        $tmp[$i]['retail_price'] = $day['retail_price'];
                        $tmp[$i]['one_stock']    = $day['oneStock'] ;//单日库存
                        $tmp[$i]['already_sold'] = $day['already_sold'];//已售数量
                        if ($day['oneStock'] > 0) {
                           $tmp[$i]['one_stock'] = $day['oneStock'] - $day['already_sold'];//剩余
                        }
                    }
                }else{
                    $tmp[$i]['sales_id']     = $data['id'];//销售方案id
                    $tmp[$i]['date']         = date($format, $i);
                    $tmp[$i]['cost_price']   = $data['costPrice'];
                    $tmp[$i]['sale_price']   = $data['salePrice'];
                    $tmp[$i]['retail_price'] = $data['retailPrice'];
                    $tmp[$i]['one_stock']    = (!$reserve || !$check_time_end || !$validPeriod) ? 0 : $data['DayStock'] ;//单日库存
                    $tmp[$i]['already_sold'] = 0;//已售数量
                }

            }elseif($day && !in_array(date('w',$day['day_time']),$weeks)){
                    //该数据不在方案中
                    $tmp[$i]['day_id']        = $day['id'];//单日表id
                    $tmp[$i]['sales_id']      = $data['id'];//销售方案id
                    $tmp[$i]['date']          = date($format, $i);
                    $tmp[$i]['cost_price']    = $day['cost_price'];
                    $tmp[$i]['sale_price']    = $day['sale_price'];
                    $tmp[$i]['retail_price']  = $day['retail_price'];
                    $tmp[$i]['one_stock']     =  (!$reserve || !$check_time_end || !$validPeriod) ? 0 : $day['oneStock'] ;//单日库存
                    $tmp[$i]['already_sold']  = $day['already_sold'];
            }
        }
        
        return $tmp;

    }
    
    /**
     * [salesExpire 销售方案是否过期]
     * @Author   ZhouYunpeng
     * @DateTime 2020-08-19
     * @param    [type]      $goods_id [description]
     * @return   [type]                [description]
     */
    public function salesExpire($goods_id)
    {
      $sales = $this->where(['goods_id'=>$goods_id,'sales_status'=>1])->find();
      if ($sales) {
         return true;
      }else{
         return false;
      }
    } 

    
    /**
     * [priceExceed 加价金额不能超过销售价格]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-25
     * @param    [type]      $markup_price [description]
     * @param    [type]      $goods_id     [description]
     * @return   [type]                    [description]
     */
    public function priceExceed($markup_price,$goods_id)
    {

       $list = $this->where(['goods_id' => $goods_id,'sales_status' => 1])->select();
        foreach ($list as $sales){
            if ($markup_price > $sales['salePrice']){
                return false;
            }
        }
       return true;
    }


    /**
     * [minPrice 商品销售方案最低销售价]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-25
     * @param    int         $goods_id [description]
     * @return   [type]                [description]
     */
    public function minPrice(int $goods_id)
    {

        return $this->where(['goods_id' => $goods_id,'sales_status' => 1])->min('salePrice');
    }

    /**
     * [minCost 最低成本价]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-25
     * @param    int         $goods_id [description]
     * @return   [type]                [description]
     */
    public function minCost(int $goods_id)
    {
        return $this->where('goods_id',$goods_id)->min('costPrice');
    }


    /**
     * [playDate 时段票获取游玩日期]
     * @Author   ZhouYunpeng
     * @DateTime 2020-12-25
     * @param    array       $calendar [description]
     * @param    [type]      $goods_id [description]
     * @return   [type]                [description]
     */
    public function playDate($calendar = [], $goods_id)
    {
        $sales = $this->get(['goods_id'=>$goods_id,'sales_status'=>1]);
        list($start,$end) = Time::today();
        $play_time = $start;//游玩时间默认当天
        if ($sales['startTime'] > $play_time){
            //销售方案开始时间大于当前时间，提前购买时间默认为销售方案开始时间
            $play_time = $sales['startTime'];
        }
        $data = [];
        foreach ($calendar as $value){
            if ($value['one_stock'] > 0 || $value['one_stock'] == -1){
                if (strtotime($value['date']) >= $play_time){
                    $data = $value;
                    break;
                }
            }
        }
        if (!$data){
            $data = end($calendar);
        }
        return $data;
    }




}